package com.qingxin.park.service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.qingxin.park.entity.ParkBlockPlant;
import com.qingxin.park.entity.ProRecord;
import com.qingxin.park.entity.ProRecordMaterial;
import com.qingxin.park.entity.ProRecordView;
import com.qingxin.repertory.entity.RepertoryAccount;
import com.qingxin.repertory.service.RepertoryAccountService;
import com.qingxin.sys.dao.Querier;
import com.qingxin.sys.dao.Updater;
import com.qingxin.sys.entity.LoginUser;
import com.qingxin.sys.entity.MyUploadFileParam;
import com.qingxin.sys.mvc.PageParam;
import com.qingxin.sys.mvc.Pager;
import com.qingxin.sys.mvc.SysError;
import com.qingxin.sys.service.BaseService;
import com.qingxin.sys.support.SystemCfg;
import com.qingxin.sys.utils.BeanUtil;
import com.qingxin.sys.utils.StringUtils;


/**
 * 生产环节记录（农事作业信息）
 * @author Administrator
 *
 */
@Service
public class ProRecordService extends BaseService<ProRecord, String> {
	
	@Autowired
	private ParkBlockPlantService parkBlockPlantService;
	
	@Autowired
	private ProRecordImgsService proRecordImgsService;
	@Autowired
	private ProRecordMaterialService proRecordMaterialService;
	
	@Autowired
	private RepertoryAccountService repertoryAccountService;
	
	
	/**
	 * 农事作业列表分页数据
	 * @param parkid
	 * @param blockid
	 * @param begin
	 * @param end
	 * @param pageParam
	 * @param loginUser
	 * @return
	 */
	public Pager list(String plantType, String parkid, String blockid, Date begin, Date end, PageParam pageParam, LoginUser loginUser){
		Querier querier = Querier.create("select new com.qingxin.park.entity.ProRecordView(" +
				"p.recordid, p.linkName, p.linkType, p.keyjob, p.workdate, p.workerName," +
				" p.plantStatus, p.cropName, p.beginTime, p.isCurrent, p.blockName)" +
				" from ProRecordView p where p.isdel='0' and p.plantType=:plantType ");
		querier.setParam("plantType", plantType);
		
		if(StringUtils.isNotEmpty(parkid)){
			querier.append(" and p.parkid=:parkid");
			querier.setParam("parkid", parkid);
			
			if(!SystemCfg.isDataAdminUser(loginUser)){
				querier.append(" and p.blockid in (select distinct v.parkBlock.blockid from SysUserBlockRel v where v.sysUser.userid=:userid)");
				querier.setParam("userid", loginUser.getUserid());
			}
		}else{
			querier.append(" and p.blockid=:blockid");
			querier.setParam("blockid", blockid);
		}
		
		if(begin != null){
			querier.append(" and p.workdate >= :beginTime ");
			querier.setParam("beginTime", begin);
		}
		if(end != null){
			querier.append(" and p.workdate <= :endTime ");
			querier.setParam("endTime", end);
		}
		
		querier.append(pageParam.getOrderby(" order by p.workdate desc"));
		
		Pager pager = pageByQuerier(querier, pageParam);
		return pager;
	}
	
	
	@SuppressWarnings("unchecked")
	public List<ProRecordView> listForExport(String plantType, String parkid, String blockid, Date begin, Date end, LoginUser loginUser){
		Querier querier = Querier.create("from ProRecordView p where p.isdel='0' and p.plantType=:plantType ");
		querier.setParam("plantType", plantType);
		
		if(StringUtils.isNotEmpty(parkid)){
			querier.append(" and p.parkid=:parkid");
			querier.setParam("parkid", parkid);
			
			if(!SystemCfg.isDataAdminUser(loginUser)){
				querier.append(" and p.blockid in (select distinct v.parkBlock.blockid from SysUserBlockRel v where v.sysUser.userid=:userid)");
				querier.setParam("userid", loginUser.getUserid());
			}
		}else{
			querier.append(" and p.blockid=:blockid");
			querier.setParam("blockid", blockid);
		}
		
		if(begin != null){
			querier.append(" and p.workdate >= :beginTime ");
			querier.setParam("beginTime", begin);
		}
		if(end != null){
			querier.append(" and p.workdate <= :endTime ");
			querier.setParam("endTime", end);
		}
		
		querier.append(" order by p.workdate desc");
		
		return listByQuerier(querier);
	}
	
	
	
	
	@SuppressWarnings("unchecked")
	public List<ProRecordView> listProRecord(String plantid){
		List<ProRecordView> list = listByHql("from ProRecordView p where p.plantid=? order by p.workdate desc", plantid);
		return list;
	}
	
	
	
	/**
	 * 获取生产环节记录信息
	 * @param recordid
	 * @return
	 */
	public ProRecordView getProRecordView(String recordid){
		ProRecordView recordView = (ProRecordView) getByHql("from ProRecordView p where p.recordid=?", recordid);
		return recordView;
	}
	
	
	/**
	 * app获取生产环节记录信息
	 * @param recordid
	 * @return
	 */
	public ProRecord getProRecord(String recordid){
		ProRecord record = get(recordid);
		if(record != null){
			record.getProRecordImgses();
			record.getProRecordMaterials();
		}
		return record;
	}
	
	/**
	 * 添加种植信息
	 * @param proRecord
	 * @param plantid
	 * @param loginUser
	 * @param request
	 * @return
	 */
	public SysError add(ProRecord proRecord, String plantid, MyUploadFileParam uploadFileParam,
			String materialid, Double materialAmount, LoginUser loginUser, HttpServletRequest request)throws Exception{
		ParkBlockPlant plant = parkBlockPlantService.get(plantid);
		if(plant == null){
			return new SysError("该地块没有可用种植信息，请先到“种植管理”模块添加种植信息");
		}
		
		proRecord.setParkBlockPlant(plant);
		
		Date now = new Date();
		proRecord.setCreateTime(now);
		proRecord.setUpdateTime(now);
		proRecord.setCreateBy(loginUser.getLogin_name());
		proRecord.setUpdateBy(loginUser.getLogin_name());
		
		proRecord.setKeyjob("1");
		proRecord.setJobname(proRecord.getLinkName());
		proRecord.setPlantStatus(plant.getPlantStatus());
		
		proRecord.setIsdel("0");
		
		this.save(proRecord);
		
		proRecordImgsService.add(proRecord.getRecordid(), uploadFileParam, loginUser);
		
		proRecordMaterialService.add(proRecord.getRecordid(), materialid, materialAmount, loginUser, request);
		
		return null;
	}
	
	
	/**
	 * 修改种植信息
	 * @param proRecord
	 * @param loginUser
	 * @param request
	 * @return
	 */
	public SysError update(ProRecord proRecord, MyUploadFileParam uploadFileParam, String materialid, LoginUser loginUser, HttpServletRequest request){
		ProRecord old = getSafeEntity(proRecord.getRecordid());
		if(old==null){
			return new SysError("参数错误");
		}
		proRecord.setJobname(proRecord.getLinkName());
		//String fields = "linkid,linkName,linkType,jobname,workdate,worktime,worker,workerName,remark";
		String fields = "jobname,workdate,worktime,worker,workerName,remark";
		BeanUtil.setTargetFields(old, proRecord, fields, true);
		
		old.setUpdateBy(loginUser.getLogin_name());
		old.setUpdateTime(new Date());
		
		Updater<ProRecord> updater = new Updater<>(old, fields+",updateBy,updateTime");
		this.update(updater);
		
		proRecordImgsService.add(proRecord.getRecordid(), uploadFileParam, loginUser);
		//proRecordMaterialService.add(proRecord.getRecordid(), materialid, loginUser);
		return null;
		
	}
	
	
	/**
	 * 删除一条记录
	 * @param recordid
	 * @param deleteType 删除类型：1清理数据、2错误数据（该类型将执行使用农资回收操作）
	 * @param loginUser
	 * @param request
	 * @return
	 */
	public Object deleteOne(String recordid, String deleteType, LoginUser loginUser, HttpServletRequest request){
		ProRecord record = getSafeEntity(recordid);
		if(record == null){
			return new SysError("信息不存在");
		}
		
		if("2".equals(deleteType)){
			ProRecordMaterial recordMaterial = proRecordMaterialService.getRecordMaterial(recordid);
			if(recordMaterial != null){
				ProRecordView proRecordView = getProRecordView(recordid);
				String accountRemark = proRecordView.getParkName()+"-"+proRecordView.getBlockName()
						+"-"+proRecordView.getCropName()+"于"+new SimpleDateFormat("yyyy-MM-dd").format(new Date())+"回收";
				
				RepertoryAccount account = new RepertoryAccount(null, recordMaterial.getMaterialid(),
						new BigDecimal(recordMaterial.getAmount().doubleValue()),
						new Date(), "2", accountRemark, loginUser.getUsername(), loginUser.getLogin_name(), new Date());
				
				SysError err = repertoryAccountService.add(account, recordMaterial.getMaterialid(), loginUser, request);
				if(err != null){
					return err;
				}
			}
		}
		
		record.setIsdel("1");
		Updater<ProRecord> updater = new Updater<>(record, "isdel");
		this.update(updater);
		
		return null;
	}
	
	
//	/**
//	 * 删除种植信息
//	 * @param recordids
//	 * @param loginUser
//	 * @param request
//	 * @return
//	 */
//	public Object delete(String[] recordids, LoginUser loginUser, HttpServletRequest request){
//		for(String recordid : recordids){
//			ProRecord proRecord = get(recordid);
//			if(proRecord==null){
//				continue;
//			}
//			
//			this.delete(proRecord);
//		}
//		
//		return null;
//	}
	
	
	
}
